<?
/***********************************/
/*  CLASSI PER L'AMMINISTRAZIONE   */
/*              				   */
/***********************************/

error_reporting(E_ERROR|E_PARSE);
include ('FFxml.class.php');

/* QUERER A DATABASE */
class DBmanager {
	
	function DBmanager($user, $pwd, $host, $dbname) {
		$this->user = $user;
		$this->pwd = $pwd;
		$this->host = $host;
		$this->dbName = $dbname;
		
		$this->conn = mysql_connect ($host, $user, $pwd) or die ("Could not connect to database");
		mysql_select_db ($dbname) or die ("non trovo il database");
	}
	
	function query($query) {
		if($res = mysql_query(strToLower($query), $this->conn)) {
			$return = array();
			for($i=0; $row = mysql_fetch_array($res); $i++) {
				$return[$i] =$row;
			}
			return $return;
		} else return 'QUERY_ERROR';
	}
	
	function editQuery($query) {
		if(mysql_query($query, $this->conn)) return true;
		else return false;
	}
	
	function getTablesName() {
		$tables = $this->getTables();
		$this->tablesName = array();
		while($this->tabs = mysql_fetch_row($this->tablesList)) {
			array_push($this->tablesName, $this->tabs[0]);
		}
		return $this->tablesName;
	}
	
	function getNumFields($tabella) {
		$this->listFields = mysql_list_fields($this->dbName, $tabella, $this->conn);
		$this->numFields = mysql_num_fields($this->listFields);
		return $this->numFields;
	}
	
	
	function getFields($tabella) {
		//trovo nome e tipo di campo
		$campo = array();
		$numFields = $this->getNumFields($tabella);
		$listField = mysql_list_fields($this->dbName, $tabella, $this->conn);
		for($i=0; $i < $numFields; $i++) {
			$this->fieldsName[$i] = mysql_field_name($listField, $i);
			$this->fieldsType[$i] = mysql_field_type($listField, $i);
			$campo[$this->fieldsName[$i]] = $this->fieldsType[$i];
		}
		return $campo;
	}
	
	function getIdField($tabella) {
		// Suppongo che, come mia impostazione, l'ID sia sempre alla posizione ZERO
		$listField = mysql_list_fields($this->dbName, $tabella, $this->conn);
		return mysql_field_name($listField, 0);
	}
	
	function getFieldType($tabella, $field) {
		$fields = $this->getFields($tabella);
		foreach($fields as $fieldName => $type) {
			if($fieldName == $field) return $type;
		}
	}
	
	function getTables() {
		$this->tablesList = mysql_list_tables($this->dbName);
		return $this->tablesList;
	}
	
	function getDatasCount($table) {
		return $this->query("select count(*) as tot from $table");
	}
	
	function date_format($date) {
		$newDate = explode("-", $date);
		return $newDate[2]."/".$newDate[1]."/".$newDate[0];
	}
	
	function date_split($date) {
		$newDate = explode("-", $date);
		return $newDate;
	}
}


/* Classe per gestire le tabelle */

class table {
	
	function table($table, $tableConf = null) {
		
		global $_CONF;
		global $_DB;
		$this->table = $table;
		$this->query = "SELECT * FROM ".$this->table;
		echo "<h1>query: " . $this->query . "</h1>";
		$this->editQuery = "SELECT * FROM ".$this->table;
		if($tableConf) $this->CONF = $tableConf;
		else $this->CONF = $_CONF->get("CONFIG>TABLES>TABLE.name=".$this->table.".node");
		
		$this->manageSettings();		// Prende impostazione di SESSIONE, CONFIGURAZIONE o GET
		
	}	
			
	function getIdField() {
		return $this->fieldsName[$i];
	}
	
	function removeFile($file, $dir) {
		if(unlink($dir.$file)) return true;
		else return false;
	}
	
	function setCrone($croneName, $table, $timedFor, $params) {
		global $_CONF;
		$crones = $_CONF->get("TABLE>CRONES.childNodes", $this->CONF);
		if($_CONF->get("TABLE>CRONES.node", $this->CONF) === false) {
			$_CONF->appendNewNode("CONFIG>TABLES>TABLE.name=".$table.".node", $_CONF->createNode(array("CRONES")));
		}
		$newCrone = $_CONF->createNode(array(
			"CRONE",
			"id=".count($_CONF->get("TABLE>CRONES.childNodes", $this->CONF)),
			"name=$croneName",
			"timedFor=$timedFor",
			"params=$params"
		));
		$_CONF->appendNewNode("CONFIG>TABLES>TABLE.name=".$table.">CRONES.node", $newCrone);
		$_CONF->saveBuiltXML();
		$_CONF->loadFile($_CONF->xmlFile);
	}
	
	function deleteCrone($croneId, $table) {
		global $_CONF;
		_log("Remove Crone (CONFIG>TABLES>TABLE.name=".$table.">CRONES>CRONE.id=".$croneId.".node)");
		$_CONF->remove("CONFIG>TABLES>TABLE.name=".$table.">CRONES>CRONE.id=".$croneId.".node");
		$_CONF->saveBuiltXML();
	}
	
	function checkCrones() {
		global $_CONF;
		$crones = $_CONF->get("TABLE>CRONES.childNodes", $this->CONF);
		if($crones !== false) {
			foreach($crones as $crone) {
				$croneTime = $_CONF->get("CRONE.timedfor", $crone);
				if(date("Y-m-d") >= $croneTime) {
					$croneName = $_CONF->get("CRONE.name", $crone);
					$croneId = $_CONF->get("CRONE.id", $crone);
					$croneParams = $_CONF->get("CRONE.params", $crone);
					$sep = $_CONF->get("CONFIG>ADMIN>MULTIFIELDSEPARATOR.nodeValue");
					$croneParams = explode($sep, $croneParams);
					_log("Run crone '$croneName' for ".$this->table);
					$return = runCrone($croneName, $croneParams);
					if ($return['status'] == "OK") {	// Crone andato a buon fine
						$this->deleteCrone($croneId, $this->table);
						_logToPage("Eseguito CRONE (".$return['title']." - ".$return['status'].")");
					} else {
						$this->deleteCrone($croneId, $this->table);
						_logToPage("CRONE execution Failed! (".$return['title']." - ".$return['status']." - ".$return['error_detail'].")");
					}
				}
			}
		}
	}
	
	function uploadFile($field) {
		global $_CONF;
		$_ERROR = false;
		
		if(isset($_FILES[$field]['name'])) {
			$uploadDir = $_CONF->get('CONFIG>ADMIN>ADMINLOADINGPATH.nodeValue');
			$dir = $_SERVER['DOCUMENT_ROOT'].$uploadDir.$this->table."/";
			if(!is_dir($dir)) {
				echo $_SERVER['DOCUMENT_ROOT'].$uploadDir.$this->table . " non trovata<br>Devo crearla<br>";
				if(mkdir($dir, 0777)) {
					chmod($dir, 0777);
				} else {
					$_ERROR = 'Impossibile trovare e creare la directory';
				}
			}
			if(is_dir($dir)) {
			 	echo "<br />Directory trovata<br />";
				$fileName = str_replace(" ", "-", $_FILES[$field]['name']);
				echo "Filename: " . $fileName;
				$fileName = $this->checkFileName($fileName, $dir);
				$fileNameTemp = $_FILES[$field]['tmp_name'];
				if(move_uploaded_file($fileNameTemp, $dir.$fileName)) {
					echo "<strong>WELL DONE!</strong>";
					return $fileName;
				} else {
					$_ERROR = 'Impossibile copiare il file nella directory specificata';
				}
			} else {
				$_ERROR = 'Impossibile trovare la directory specificata';
			}
			
		} else {
			$_ERROR = 'Impossibile trovare il file da caricare';
		}
		if($_ERROR) return false;
	}
	
	function checkFileName($fileName, $dir) {
		$i = 0;
		$suf = "";
		while(is_file($dir.$suf.$fileName)) {
			$i++;
			$suf = $i;
		}
		return $suf.$fileName;
	}
	
	function getCrossFieldsList($ref, $listField) {
		$return = array();
		$query = "SELECT $listField,$ref FROM ".$this->table;
		$result = mysql_query($query, $_DB->conn);
		while($row = mysql_fetch_array($result)) {
			$return[$row[$ref]] = $row[$listField];
		}
		return $return;
	}
	
	function getUploadDirFiles($selected = null) {
		
		global $_CONF;
		
		$loadPath = $_CONF->get("CONFIG>ADMIN>ADMINLOADINGPATH.nodeValue");
		$openDir = $_SERVER['DOCUMENT_ROOT'].$loadPath.$this->table;
		if (is_dir($openDir)) {
			if ($dh = opendir($openDir)) {
				while (($file = readdir($dh)) !== false) {
					if($file != "." && $file != "..") {
						if($selected && $file == $selected) $code .= '<option value="'.$file.'" selected>'.$file.'</option>';
						else $code .= '<option value="'.$file.'">'.$file.'</option>';
					}
				}
				closedir($dh);
				return $code;
			} else return false;
		} else {
			return false;
		}
		
	}
	
	function setFilter($filterType, $filterValue, $filterField) {
		if(strpos($this->query, "where") === false) $this->query .= " where";
		switch($filterType) {
			case 'noteq':
				$this->query .= " $filterField != ".((is_numeric($filterValue)?$filterValue:"'".$filterValue."'"));
				break;
			case 'eq':
				$this->query .= " $filterField = ".((is_numeric($filterValue)?$filterValue:"'".$filterValue."'"));
				break;
			case 'present':
				$this->query .= " $filterField like '%".$filterValue."%'";
				break;
			case 'notpresent':
				$this->query .= " $filterField not like '%".$filterValue."%'";
				break;
			case 'higher':
				$this->query .= " $filterField > $filterValue";
				break;
			case 'lower':
				$this->query .= " $filterField < $filterValue";
				break;
		}
	}
	
	function manageSettings() {
		
		global $_CONF;
		global $_DB;		
		
		if($_GET['action'] == 'EDIT') {
			$this->editQuery .= " where ".$_GET['editField']." = ".$_GET['editId'];
		}
		
		// Filtri
		if($_GET['action'] == "SetFilter") {
			foreach($_DB->getFields($this->table) as $name => $type) {	// Ciclo i campi alla ricerca di quelli filtrati
				if($_POST[$name . '_filterValue'] != "") {
					if(!isset($_SESSION['FF']['FILTERS'])) $_SESSION['FF']['FILTERS'] = array();
					$_SESSION['FF']['FILTERS'][$this->table] = array();		// Resetto l'array della tabella per reset
					$_SESSION['FF']['FILTERS'][$this->table][$name] = $_POST[$name . '_filterType'] . "=>" . $_POST[$name . '_filterValue'];
					if($_POST[$name . '_filterValue2'] != "") {
					$_SESSION['FF']['FILTERS'][$this->table][$name] .= "&&".$_POST[$name . '_option2']."&&" . $_POST[$name . '_filterType2'] . "=>" . $_POST[$name . '_filterValue2'];
					}
				}
			}
			// Cancello la pagina corrente se imposto un filtro
			unset($_SESSION['FF'][$this->table]['dataPerPage']);
		}
		
		if($_GET['action'] == "deleteFilter") {
			unset($_SESSION['FF']['FILTERS'][$this->table]);
		}
		
		if(isset($_SESSION['FF']['FILTERS'][$this->table])) {		// Ho un filtro per questa tabella.
			foreach($_SESSION['FF']['FILTERS'][$this->table] as $field => $filterSetup) {
				$filters = explode("&&", $filterSetup);
				foreach($filters as $filter) {
					if($filter == "and" || $filter == "or") {
						$this->query .= " ".$filter;
					} else {
						list ($filterType, $filterValue) = explode("=>", $filter);
						if($filterType != "" && $filterType != null) {	// Setto il filtro
							$this->setFilter($filterType, $filterValue, $field);
						}
					}
				}
			}
		}
		
		// Ordinamento
		if($this->getSetting('orderField')) {
			if($_GET['orderField']) {
				$orderField = $_GET['orderField'];
				$orderDir = $this->getSetting('orderDir');
				if($orderDir == 'DESC') $orderDir = 'ASC';
				else $orderDir = 'DESC';
			} else {
				$orderDir = $_CONF->get("CONFIG>TABLES>TABLE.name=".$this->table.".orderDir");
				$orderField = $_CONF->get("CONFIG>TABLES>TABLE.name=".$this->table.".orderField");
				if(!$orderDir) $orderDir = 'DESC';
			}
			$_SESSION['FF'][$this->table]['orderDir'] = $orderDir;
			$_SESSION['FF'][$this->table]['orderField'] = $orderField;
			$this->query .= " ORDER BY $orderField $orderDir";
		}
		
		// Limite
		$this->dataPerPage = intval($this->dataPerPage);
		if($this->dataPerPage = $this->getSetting('dataPerPage')) {
			$totDatas = $_DB->query("select count(*) as tot from ".$this->table);
			$_SESSION['FF'][$this->table]['dataPerPage'] = intval($this->dataPerPage); 
			if(intval($this->dataPerPage) < intval($totDatas[0]['tot'])) {
				if($_GET['currentPage'] || $_SESSION['FF'][$this->table]['currentPage']) {
					$totPage = ceil($totDatas[0]['tot'] / $this->dataPerPage);
					$this->currentPage = ($_GET['currentPage'])?$_GET['currentPage']:$_SESSION['FF'][$this->table]['currentPage'];
					if($this->currentPage > $totPage) $this->currentPage = $totPage;
					
					$this->query .= " LIMIT ".(($this->currentPage-1)*$this->dataPerPage).", ".$this->dataPerPage;
					$_SESSION['FF'][$this->table]['currentPage'] = $this->currentPage;
				} else {
					$this->query .= " LIMIT 0, ".$this->dataPerPage;
					$this->currentPage = $_SESSION['FF'][$this->table]['currentPage'] = 1;
				} 
			} else {
				// Cancello il paginatore
				unset($this->currentPage);
				unset($_SESSION['FF'][$this->table]['currentPage']);
			}
		}
		
	}
	
	function getSetting($setting) {
		
		global $_CONF;
		
		if (isset($_GET[$setting])) return $_GET[$setting];
		else if(isset($_SESSION['FF'][$this->table][$setting])) return $_SESSION['FF'][$this->table][$setting]; 
		else if ($_CONF->get("TABLE.".$setting, $this->CONF)) return $_CONF->get("TABLE.".$setting, $this->CONF);
		else return false;
		
	}	
	
	function getContentHeaders() {
		
		global $_DB;
		global $_CONF;
		echo '<tr class="header">'.
		'<th><a href="#" onclick="FF.contents.checkAllRows();" class="btnCheckAll">ALL</a></th>'.
		'<th colspan="2" width="5%">&nbsp;</th>';
		
		$listHeaders = $_DB->getFields($this->table);
		foreach($listHeaders as $name => $type) {
			$_FIELD = $_CONF->get("TABLE>FIELDS>FIELD.name=".$name.".node", $this->CONF);
			if($this->isFieldVisible($name)) {
				$titolo = $_CONF->get("FIELD.title", $_FIELD);
				echo '<th title="'.$_CONF->get("FIELD>DESCRIPTION.nodeValue", $_FIELD).'" '.(($_SESSION['FF'][$this->table]['orderField'] == $name)?' class="ordering"':'').' nowrap>
				<a href="content.php?orderField='.$name.'&table='.$this->table.'" class="btnOrder">'.(($titolo)?$titolo:$name);
				
				if($_SESSION['FF'][$this->table]['orderField'] == $name) {
					if($_SESSION['FF'][$this->table]['orderDir'] == "ASC") echo ' <img src="i/asc.gif" />';
					else echo ' <img src="i/dec.gif" />';	
				}
				echo '</a>';
				if($_CONF->get("TABLE>FIELDS>FIELD.name=$name.type", $this->CONF) == "filesystem") {
					// E' un file.
					$imgPath = $_CONF->get("CONFIG>ADMIN>ADMINIMAGEPATH.nodeValue");
					if($this->getSetting("showImage_" . $name) == "show") {
						echo '<a href="content.php?showImage_'.$name.'=hide"><img src="'.$imgPath.'hide.gif" border="0" hspace="3" /></a>';
					} else {
						//echo '<a href="content.php?showImage_'.$name.'=show"><img src="'.$imgPath.'view.gif" border="0" /></a>';
						$path = $_CONF->get("CONFIG>ADMIN>ADMINLOADINGPATH.nodeValue").$this->table."/";
						echo '<a href="#" onclick="FF.contents.showImagesThumb(\''.$name.'\', \''.$path.'\', '.$_CONF->get("CONFIG>UI>IMGPREVIEWSIZE.nodeValue").', this);"><img src="'.$imgPath.'view.gif" border="0" hspace="3" /></a>';
					}
				}
				echo '</th>';
			}
		}
		
		echo '</tr>';		
			
	}
	
	function getPager() {
		
		global $_DB;
		if($this->currentPage) {
			// C'è paginatore
			echo '<div class="pager tabStyle">';
			
			if(isset($_SESSION['FF']['FILTERS'][$this->table])) {
				$filterQuery = str_replace("SELECT *", "SELECT count(*) as tot", $this->query);
				$filterQuery = explode("ORDER BY", $filterQuery);
				$totDatas = $_DB->query($filterQuery[0]);
			} else $totDatas = $_DB->query("select count(*) as tot from ".$this->table);
			
			$totPage = ceil($totDatas[0]['tot'] / $this->dataPerPage);
			if(($this->currentPage-1) > 1) echo '<a href="content.php?currentPage=1"><<</a>';
			if($this->currentPage > 1) echo ' &nbsp;<a href="content.php?currentPage='.($this->currentPage-1).'"><</a>';
			echo " &nbsp;Pagina <strong>".$this->currentPage."</strong> di ".$totPage;
			if($_GET['action'] == "SetFilter" || isset($_SESSION['FF']['FILTERS'])) { echo ' <a href="#"><em>(vedi filtro)</em></a>'; }
			if($this->currentPage < $totPage) echo ' &nbsp;<a href="content.php?currentPage='.($this->currentPage+1).'">></a>';
			if(($this->currentPage+1) < $totPage) echo ' &nbsp;<a href="content.php?currentPage='.$totPage.'">>></a>';
			
			echo '</div>';
		}

	}
	
	function showCrossField($data, $_FIELD) {	
		global $_CONF; global $_DB;
		
		$tabella = $_CONF->get("FIELD>CROSS.table", $_FIELD);
		$ref = $_CONF->get("FIELD>CROSS.ref", $_FIELD);
		$title = $_CONF->get("FIELD>CROSS.title", $_FIELD);
		$multiple = $_CONF->get("FIELD.multiple", $_FIELD);
		if($multiple == "true") {
			$sep = $_CONF->get("CONFIG>ADMIN>MULTIFIELDSEPARATOR.nodeValue");
			$multiValues = explode($sep, $data);
			$data = "";
			foreach($multiValues as $id) {
				$cross = $_DB->query("select $ref,$title from $tabella where $ref = '$id'");
				$data .= $cross[0][$title]." &nbsp;";
			}
			if($data == "") $data = "&nbsp;";
			return $data;
		} else {
			$cross = $_DB->query("select $ref,$title from $tabella where $ref = '$data'");
			if($cross != false && $cross != "QUERY_ERROR") return $cross[0][$title];
			else return false;
		}
	}
	
	function showVirtualCrossField($data, $_FIELD) {
		global $_CONF; global $_DB;
		$data = $_CONF->get("FIELD>VIRTUALCROSS>DATA.value=$data.label", $_FIELD);
		if($data == "") $data = "&nbsp;";
		return $data;
	}
	
	function showFilesystem($data, $fieldName) {
		global $_CONF;
		if($this->getSetting("showImage_".$fieldName) == "show") {
			$imgPath = $_CONF->get("CONFIG>ADMIN>ADMINLOADINGPATH.nodeValue").$this->table . "/" . $data;
			$data =  '<img src="'.$imgPath.'" height="50">';
		}
		if($data == "") $data = "&nbsp;";
		return $data;
	}
	
	function showBlob($data) {
		$data = substr(strip_tags($data), 0, 30);
		if($data == "") $data = "&nbsp;";
		return $data;
	}
	
	function showDate($data) {
		
		global $_DB;	global $_MSG;
		$data = $_DB->date_format($data);
		$gma = explode("/", $data);
		$data = '<div class="dataWrapper calendar"><span class="day">'.$gma[0].'</span><span class="month">'.$_MSG['calendar_months'][$gma[1]].'</span><br><span style="color:#999; font-size:10px">'.$gma[2].'</span></div>';
		return $data;
	}
	
	function showData($data, $_FIELD, $id) {
		
		global $_CONF;	global $_DB;	global $_MSG;
		if(!is_array($_FIELD)) $fieldName = $_FIELD;
		else $fieldName = $_CONF->get("FIELD.name", $_FIELD);
		
		$type = $_DB->getFieldType($this->table, $fieldName);
		$fieldCross = $_CONF->get("FIELD>CROSS.node", $_FIELD);
		$fieldVCross = $_CONF->get("FIELD>VIRTUALCROSS.childNodes", $_FIELD);
		$fieldDescription = $_CONF->get("FIELD>DESCRIPTION.nodeValue", $_FIELD);
		$fieldRowId = $this->table.'>'.$id.'>'.$fieldName;
		
		if($fieldCross) {
					
			echo '<td class="crossField"><div class="datasBox" id="'.$fieldRowId.'" name="'.$fieldName.'" ondblclick="FF.contents.fastEdit(this)" title="'.$fieldDescription.'">';
			echo $this->showCrossField($data, $_FIELD);			
			echo "</div></td>";
			
		} else if ($fieldVCross) {
			
			echo '<td class="vcrossField"><div class="datasBox" id="'.$fieldRowId.'" name="'.$fieldName.'" ondblclick="FF.contents.fastEdit(this)" title="'.$fieldDescription.'">';
			echo $this->showVirtualCrossField($data, $_FIELD);
			echo "</div></td>";
			
		} else if($_CONF->get("FIELD.type", $_FIELD) == "filesystem") {
			
			echo '<td class="imageField_'.$fieldName.'"><div class="datasBox" id="'.$fieldRowId.'" name="'.$fieldName.'" ondblclick="FF.contents.fastEdit(this)" title="'.$fieldDescription.'">';
			echo $this->showFilesystem($data);
			echo '</div></td>';
			
		} else {
			echo '<td><div class="datasBox" id="'.$fieldRowId.'" name="'.$fieldName.'" ondblclick="FF.contents.fastEdit(this)" title="'.$fieldDescription.'">&nbsp;';
			switch($type) {
				case "blob": 
					echo $this->showBlob($data);
					break;
				/*
				case "string":
					break;
				case "real":
					break;
				case "int":
					break;
				*/
				case "date":
					echo $this->showDate($data);
					break;
				default: echo substr($data, 0, 300);
			}
			echo '</div></td>';
		}		
		
	}
	
	function isFieldVisible($fieldName) {
		
		global $_CONF;
		
		if(($_SESSION['FF']['logType'] == 0 && $_CONF->get("CONFIG>TABLES>TABLE.name=".$this->table.">FIELDS>FIELD.name=$fieldName.adminfield") == "true") || ($_CONF->get("CONFIG>TABLES>TABLE.name=".$this->table.">FIELDS>FIELD.name=$fieldName.visible") == "false")) return false;
		else return true;
	}
	
	function getVirtualCrossSelect($name, $data, $_FIELD)
	{
		global $_CONF;
		
		echo '<select name="'.$name.'"><option value="--">Seleziona..</option>';
		$virtualCross = $_CONF->get("FIELD>VIRTUALCROSS.childNodes", $_FIELD);
		
		foreach($virtualCross as $row => $value) {
			if($data == null)		// Siamo in insert
				echo '<option value="'.$_CONF->get("DATA.value", $value).'" '.(($_CONF->get("DATA.value", $value) == $default)?"selected":"").'>' . $_CONF->get("DATA.label", $value) . '</option>';
			else 
				echo '<option value="'.$_CONF->get("DATA.value", $value).'" '.(($data == $_CONF->get("DATA.value", $value))?"selected":"").'>' . $_CONF->get("DATA.label", $value) . '</option>';
		}
		echo '</select>';
	}
	
	function getCrossSelect($name, $data, $_FIELD)
	{
		global $_CONF;
		global $_DB;
		
		$tabella = $_CONF->get("FIELD>CROSS.table", $_FIELD);
		$ref = $_CONF->get("FIELD>CROSS.ref", $_FIELD);
		$title = $_CONF->get("FIELD>CROSS.title", $_FIELD);
		
		$cross = $_DB->query("select * from $tabella");
		$multiple = $_CONF->get("FIELD.multiple", $_FIELD);
		$fieldName = $name;
		if($multiple == "true") { ?>
			
			<table>
			<tr><td>
			<strong>Valori disponibili</strong><br>
			<select id="<?=$_CONF->get("FIELD.name", $_FIELD);?>_multivalue" multiple style="height:200px ">
			<?
			$sep = $_CONF->get("CONFIG>ADMIN>MULTIFIELDSEPARATOR.nodeValue");
			$multiValues = explode($sep, $data);
			foreach($cross as $row => $value) {
				if(!in_array($value[$ref], $multiValues)) echo '<option value="'.$value[$ref].'">' . $value[$title] . '</option>';
			}
			?>
			</select>
			</td><td>
			<a href="javascript:FF.contents.moveOptions($('<?=$fieldName?>_multivalue'), $('<?=$fieldName?>_target'), $('<?=$fieldName?>_target'), $('<?=$fieldName?>'))">>></a><br>
			<br>
			<a href="javascript:FF.contents.moveOptions($('<?=$fieldName?>_target'), $('<?=$fieldName?>_multivalue'), $('<?=$fieldName?>_target'), $('<?=$fieldName?>'))"><<</a>
			</td><td>
			<strong>Valori selezionati</strong><br>
			<select name="<?=$fieldName?>_target" id="<?=$fieldName?>_target" multiple style="height:200px ">
			<?
			
			foreach($cross as $row => $value) {
				if(in_array($value[$ref], $multiValues)) echo '<option value="'.$value[$ref].'">' . $value[$title] . '</option>';
			}
			?>
			</select>
			<input type="hidden" id="<?=$fieldName?>" name="<?=$fieldName?>" value="<?=$data?>">
			</td></tr>
			</table>
			
		<? } else {
			?><select name="<?=$fieldName?>"><option value="--">Seleziona..</option><?
			foreach($cross as $row => $value) {
				echo '<option value="'.$value[$ref].'" '.(($data == $value[$ref])?"selected":"").'>' . $value[$title] . '</option>';
			}
			?></select><?
		}
	}
	
	function editData($data, $_FIELD, $type, $name, $editType) {
		
		global $_CONF;
		global $_DB;
		
		if($data == null) $data = str_replace("\'", "'", $_CONF->get("FIELD>DEFAULT.nodeValue", $_FIELD));
		
		if($_CONF->get("FIELD>CROSS.node", $_FIELD)) {
			
			echo $this->getCrossSelect($name, $data, $_FIELD);
						
		} else if ($_CONF->get("FIELD>VIRTUALCROSS.childNodes", $_FIELD)) {
			
			echo $this->getVirtualCrossSelect($name, $data, $_FIELD);
			
		} else if ($_CONF->get("FIELD.type", $_FIELD) == "filesystem") {
			
			// Generalmente immagine o comunque campo su filesystem
			$loadPath = $_CONF->get("CONFIG>ADMIN>ADMINLOADINGPATH.nodeValue");
			$imgPath = $loadPath.$this->table."/".$data;
			?>
			<table>
			<tr valign=top><td>
			<?
			if(is_file($_SERVER['DOCUMENT_ROOT'].$imgPath)) echo '<a href="'.$imgPath.'" target="_NEW" title="Vedi immagine"><img id="previewer_'.$name.'" src="'.$imgPath.'" width="150" /></a>';
			else echo '<img id="previewer_'.$name.'" src="i/imageNotFound.gif" width="150" />';
			?>
			</td>
			<td>Nome del file: <strong id="filename_<?=$name?>"><?=$data?></strong> | &nbsp;<input type="button" id="btnRemove_<?=$name?>" onclick="FF.contents.removeUploadedFile('<?=$data?>', '<?=$this->table?>', '<?=$name?>');" value="CANCELLA"><br><br>
			Seleziona da directory:<br>
				<input type="hidden" name="loadingType_<?=$name?>" value="LOAD" />
				<input type="hidden" name="remove_<?=$name?>" id="remove_<?=$name?>" value="" />
				<select id="fileSelect_<?=$name?>" name="<?=$name?>" onchange="FF.contents.selectImage('<?=$name?>',  '<?=$loadPath.$this->table."/"?>' + this.options[this.selectedIndex].value, 'SELECT');">
				<option value=""> -- </option>
				<?=$this->getUploadDirFiles($data)?>
				</select>
			<br /><br />
			Seleziona da disco:<br />
			<input type="file" name="<?=$name?>_filesystem" value="none" onchange="FF.contents.selectImage('<?=$name?>', this.value, 'BROWSE');" >
			</td></tr>
			</table>
			<?
			
		} else {
			$description = $_CONF->get("FIELD>DESCRIPTION.nodeValue", $_FIELD);
			switch($type) {
				case "string": 
					if(strpos($data, "'") !== false) $data = str_replace("'", '"', $data);
					echo '<div style="overflow:hidden;" title="'.$description.'">
					<input type="text" id="'.$name.'" name="'.$name.'" value=\''.$data.'\' style="width:300px">
					</div>';
					break;
				case "real": 
					echo '<div style="overflow:hidden;" title="'.$description.'">
					<input type="text" id="'.$name.'" name="'.$name.'" value="'.$data.'" style="width:100px" onblur="FF.contents.checkDataFormat(\'NUMERIC\', this);">
					</div>';
					break;
				case "int": 
					echo '<div title="'.$description.'"><input onblur="FF.contents.checkDataFormat(\'NUMERIC\', this);" type="text" id="'.$name.'" name="'.$name.'" value="'.$data.'" style="width:100px"></div>';
					break;
				case "date": 
					if($data == str_replace("\'", "'", $_CONF->get("FIELD>DEFAULT.nodeValue", $_FIELD)) && $data != "") 
						eval('$data = '.$data.';');
						
					echo '<div title="'.$description.'" class="field_data"><input type="text" id="'.$name.'" name="'.$name.'" value="'.$data.'" onblur="FF.contents.checkDataFormat(\'DATE\', this);"><div class="calendarButton"><a href="javascript:FF.contents.showCalendar(\'popupCal_'.$name.'\');"><img src="i/ico_calendar.gif" /></a><div id="popupCal_'.$name.'" class="calendar scal tinyscal"></div></div></div>';
					if($data != str_replace("\'", "'", $_CONF->get("FIELD>DEFAULT.nodeValue", $_FIELD))) {
						$dateArray = $_DB->date_split($data);
						echo '<script>'.
							'var options = ({ month: '.$dateArray[1].', year: '.$dateArray[0].', day: '.$dateArray[2].' });'.
							'var samplecal = new scal("popupCal_'.$name.'", "'.$name.'", options);'.
						'</script>';
					} else {	// E' il default
						
						echo '<script>'.
							'var options = ({});'.
							'var samplecal = new scal("popupCal_'.$name.'", "'.$name.'", options);'.
						'</script>';
					}
					break;
				case "blob": 
					echo '<div style="overflow:hidden;" title="'.$description.'">
					<div class="tabStyle">
						<a href="#" onclick="new nicEditor({fullPanel : true}).panelInstance(\''.$name.'_RTA\'); return false;">Textarea avanzata</a>
					</div><br clear="both" />
					<textarea style="width: 90%; height: 200px" id="'.$name.'_RTA" name="'.$name.'" class="'.$name.'">'.$data.'</textarea>
					</div>';
					break;
				default:
					if(strpos($data, "'") !== false) $data = str_replace("'", '"', $data);
					echo '<div style="overflow:hidden;" title="'.$description.'">
					<input type="text" id="'.$name.'" name="'.$name.'" value=\''.$data.'\' style="width:300px">
					</div>';
					break;
			}
		}		
	}
	

}


/* Utilities */

class utils {
	
	function utils() {
		global $_CONF;
		global $_DB;
	}
	
	function getIdsFromMultipleString() {
		
	}
	
}

?>



